package com.canbot.u05.activity.admin

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.alibaba.fastjson.JSON
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.canbot.u05.R
import com.canbot.u05.activity.*
import com.canbot.u05.bean.AdminInfoBean
import com.canbot.u05.bean.JsonResponse
import com.canbot.u05.bean.PersonData
import com.canbot.u05.glide.GlideApp
import com.canbot.u05.socket.IpMsgConst
import com.canbot.u05.utils.OkHttpUtils
import com.canbot.u05.utils.PathConst
import com.canbot.u05.widget.LoadingDialogUtils
import kotlinx.android.synthetic.main.activity_admin_face_modify.*
import java.util.*

/**
 * desc: 管理员人脸信息修改界面
 * author: xxl
 * date: 2019/6/19
 */
class AdminFaceModifyActivity : BaseActivityNoTitle() {
    private lateinit var mContext: Context
    private var adminInfoBean = AdminInfoBean()
    private var loadingDialog: Dialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_admin_face_modify)
        mContext = this
        val adminJson = intent.getStringExtra("admin")
        if (TextUtils.isEmpty(adminJson)) {
            getData()
        } else {
            adminInfoBean = JSON.parseObject(adminJson, AdminInfoBean::class.java)
            updataUI()
        }

        iv_admin_face.setOnClickListener {startActivityForResult(Intent(this@AdminFaceModifyActivity, AdminFaceGroupActivity::class.java), REQUEST_CODE) }

        btn_sure_modify_face.setOnClickListener { upLoadAdminInfo() }
    }

    /**
     * 上传管理员信息
     */
    private fun upLoadAdminInfo() {
        loadingDialog = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.updating))
        val jsonString = JSON.toJSONString(adminInfoBean)

        val params = HashMap<String, String>()
        params["adminType"] = "updateAdmin"
        params["updateAdmin"] = jsonString
        params["type"] = "face"

        OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "admin", params, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                val jsonResponse = JSON.parseObject(result, JsonResponse::class.java)
                runOnUiThread {
                    if (jsonResponse.rc == 0) {
                        showToast(getString(R.string.update_successfully))
                        cancelDialog()
                        finish()
                    } else {
                        showToast(getString(R.string.update_failed))
                        cancelDialog()
                    }
                }

            }

            override fun onFailure() {
                showToast(getString(R.string.service_error_hint))
                cancelDialog()
            }
        })
    }

    private fun getData() {
        val params = HashMap<String, String>()
        params["adminType"] = "queryAdmin"
        OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "admin", params, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                val jsonResponse = JSON.parseObject(result, JsonResponse::class.java)
                if (jsonResponse.rc == 0) {
                    val jsonStr = jsonResponse.result.toString()
                    adminInfoBean = JSON.parseObject(jsonStr, AdminInfoBean::class.java)
                    updataUI()
                } else {
                    showToast(getString(R.string.admin_not_found))
                }
            }

            override fun onFailure() = showToast(getString(R.string.service_error_hint))
        })
    }

    /**
     * 更新管理员UI
     */
    private fun updataUI() {
        runOnUiThread {
            tv_admin_name.text = resources.getString(R.string.current_admin) + adminInfoBean.adminName

            GlideApp.with(mContext).clear(iv_admin_face)
            GlideApp.with(mContext)
                    .asDrawable()
                    .load(IpMsgConst.HTTP_URL_CHEST + PathConst.FACES_ABS_DIR + adminInfoBean.picPath)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                    .skipMemoryCache(false)
                    .placeholder(R.drawable.sales_banner01)//占位图
                    .error(R.drawable.ic_picture_loadfailed)
                    .override(mContext.resources.getDimension(R.dimen.px290).toInt(), mContext.resources.getDimension(R.dimen.px290).toInt())
                    .into(iv_admin_face)
        }
    }

    /**
     * 返回选中的管理员信息
     * @param data 人脸数据
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            if(data == null){
                return
            }
            val jsonData = data.getStringExtra("personData")

            loge("jsonData:$jsonData")

            val personData = JSON.parseObject(jsonData, PersonData::class.java)

            loge(personData.toString())

            adminInfoBean.adminName = personData.name
            adminInfoBean.picPath = personData.path
            btn_sure_modify_face.visibility = View.VISIBLE

            updataUI()
        }
    }

    fun back(view: View) = finish()

    /**
     * 取消加载的Dialog
     */
    private fun cancelDialog() {
        if (loadingDialog != null && loadingDialog!!.isShowing) {
            loadingDialog?.cancel()
        }
    }

    override fun onPause() {
        super.onPause()
        cancelDialog()
    }

    companion object {

        const val REQUEST_CODE = 101
        const val RESULT_OK = 501
    }
}
